package com.wcfsy.wechat.wx.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class FileUploadUtil {
	private Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);
	private String basePath;
	private String domain;
	private String imageCatalog;

	public String getBasePath() {
		return basePath;
	}

	public void setBasePath(String basePath) {
		this.basePath = basePath;
	}

	public String getDomain() {
		return domain;
	}

	public void setDomain(String domain) {
		this.domain = domain;
	}

	public String getImageCatalog() {
		return imageCatalog;
	}

	public void setImageCatalog(String imageCatalog) {
		this.imageCatalog = imageCatalog;
	}

	public String upload(MultipartFile file) throws IOException {
		String imageFold = DateUtil
				.DateToString(new Date(), DateStyle.YYYYMMDD);
		String filePath = basePath + File.separator + imageFold;
		logger.info("filePath={}", filePath);
		File outFile = new File(filePath);
		mkdir(outFile);
		byte[] bytes = file.getBytes();
		String fileName = getFileName();
		BufferedOutputStream stream = new BufferedOutputStream(
				new FileOutputStream(new File(outFile, fileName)));
		stream.write(bytes);
		stream.close();
		StringBuffer buffer = new StringBuffer(domain);
		buffer.append(basePath.replace(basePath, "/"+imageCatalog+"/images/"));
		buffer.append(imageFold).append("/").append(fileName);
		logger.info("imagePath={}", buffer.toString());
		return buffer.toString();
	}

	private void mkdir(File file) {
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	private String getFileName() {
		String fileName = DateUtil.DateToString(new Date(),
				DateStyle.YYYYMMDDHHMMSS)+StringUtil.randomCode(4) + ".jpg";
		return fileName;
	}

}
